package com.zhang;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

/**
 * JdbcRealm测试
 * 需要在mysql的users表里添加用户
 */
public class JdbcRealmTest {

    DruidDataSource dataSource=new DruidDataSource();
    {
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root"); dataSource.setPassword("root");
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(10);
    }
    @Test
    public void testAuthentication()
    {
        JdbcRealm jdbcRealm=new JdbcRealm();
        jdbcRealm.setDataSource(dataSource);
        //用自己的表，默认的是查系统的用户表
//        String sql="select password from  test_user where user_name";
//        jdbcRealm.setAuthenticationQuery(sql);
        //查询用户权限
//       jdbcRealm.setUserRolesQuery(sql);
//        1.构建SecurityManager环境
        DefaultSecurityManager defaultSecurityManager= new DefaultSecurityManager();
        defaultSecurityManager.setRealm(jdbcRealm);
//        2.主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject=SecurityUtils.getSubject();
//        3.获取认证数据（从数据库）
        UsernamePasswordToken token =new UsernamePasswordToken("zhang","123");
        System.out.println("是否认证的结果："+subject.isAuthenticated());
        subject.login(token);
        System.out.println("是否认证的结果："+subject.isAuthenticated());
        //-------------------------------判断用户角色，查看用户权限
//        subject.checkRole("admin");
//        subject.checkPermission("user:delete");
//        subject.checkPermission("user:update"); //没有的权限

    }
}
